<?php

namespace backend\modules\rbac\models;

//use mdm\admin\models\AuthItem;
use api\modules\v1\models\Wxuser;
use backend\models\Admin;
use Pheanstalk\Exception;
use Yii;

/**
 * This is the model class for table "menu_perm".
 *
 * @property integer $menu_item_id
 * @property string $item_name
 * @property integer $menu_id
 *
 * @property AuthItem $itemName
 * @property Menu $menu
 */
class MenuPerm extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'menu_perm';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['item_name', 'menu_id'], 'required'],
            [['menu_id'], 'integer'],
            [['item_name'], 'string', 'max' => 50],
//            [['item_name'], 'exist', 'skipOnError' => true, 'targetClass' => AuthItem::className(), 'targetAttribute' => ['item_name' => 'name']],
            [['menu_id'], 'exist', 'skipOnError' => true, 'targetClass' => Menu::className(), 'targetAttribute' => ['menu_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'menu_item_id' => Yii::t('app', 'Menu Item ID'),
            'item_name' => Yii::t('app', 'Item Name'),
            'menu_id' => Yii::t('app', 'Menu ID'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getItemName()
    {
        return $this->hasOne(AuthItem::className(), ['name' => 'item_name']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenu()
    {
        return $this->hasOne(Menu::className(), ['id' => 'menu_id']);
    }

    /**
     * @inheritdoc
     * @return \backend\modules\rbac\models\query\MenuPermQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \backend\modules\rbac\models\query\MenuPermQuery(get_called_class());
    }

    /**
     * 创建menu权限
     * @param $menu_id
     * @return bool
     * @throws Exception
     */
    public function createItemMenu($menu_id)
    {
        $auth = Yii::$app->authManager;
        $createPost = $auth->createPermission("Menu@".$menu_id);
        $createPost->description = '创建菜单Menu@'.$menu_id.'权限';
        $auth->add($createPost);

        $model = new MenuPerm();
        $model->menu_id = $menu_id;
        $model->item_name = "Menu@".$menu_id;
        if(!$model->save()){
            throw new Exception(json_encode($model->errors));
        }
        return true;
    }


    /**
     * 创建角色
     * @param $name
     * @param $description
     * @return bool
     */
    public function createRole($name,$description=null)
    {
        $auth = Yii::$app->authManager;
        $createPost = $auth->createRole($name);
        if(!$description){
            $createPost->description = '创建'.$name.'角色';
        }else{
            $createPost->description = $description;
        }
        $auth->add($createPost);
        return true;
    }

    /**
     * @param $role
     * @param $item
     */
    public function PermissionToRole($role,$item)
    {
        $auth = Yii::$app->authManager;
        $parent = $auth->createRole($role);
        $child = $auth->createRole($item);
        $auth->addChild($parent,$child);
    }

    /**
     * 根据用户ID获取角色
     *
     * @param $userid
     * @return \yii\rbac\Role[]
     */
    public function getRoleByUser($userid)
    {
        $auth = Yii::$app->authManager;
        return $auth->getRolesByUser($userid);
    }

    /**
     * 添加用户角色
     *
     * @param $role
     * @param $user_id
     * @throws Exception
     */
    public function RoleToUser($role,$user_id)
    {
        $newAssignment = new AuthAssignment();
        $newAssignment->item_name = $role;
        $newAssignment->user_id = $user_id;
        if(!$newAssignment->save()){
            throw new Exception('用户赋予角色失败');
        }
    }

    /**
     * 删除用户角色
     *
     * @param $role
     * @param $user_id
     * @throws \Exception
     * @throws \Throwable
     */
    public function delRoleFromUser($role,$user_id)
    {
        $model = AuthAssignment::findOne(['user_id'=>$user_id,'item_name'=>$role]);
        $model->delete();
    }


    /**
     * 获取所有角色
     * @return \yii\rbac\Role[]
     */
    public function getRoles()
    {
        $auth = Yii::$app->authManager;
        return $auth->getRoles();
    }

    /**
     * 获取所有角色
     * @return \yii\rbac\Role[]
     */
    public function getUserByRole($name)
    {
        $userARRs = AuthAssignment::find()
            ->select('u.*,aa.*')
            ->from('auth_assignment as aa')
            ->leftJoin('admin as u','aa.user_id=u.id')
            ->where(['aa.item_name'=>$name])
            ->asArray()
            ->all();
        return $userARRs;
    }

    /**
     * 配置角色菜单权限
     *
     * @param $menuIDs
     * @param $roleName
     * @throws Exception
     * @throws \Exception
     * @throws \Throwable
     */
    public function setRoleBymenuId($menuIDs,$roleName)
    {
        $newMenuARR = array();
        foreach($menuIDs as $k=>$v) {
            $newMenuARR[] = 'Menu@'.$v;
        }

        $newChildARR = array();
        $childARR = AuthItemChild::find()->select(['child'])->where(['parent'=>$roleName])->asArray()->all();
        foreach($childARR as $k=>$v) {
            $newChildARR[] = $v['child'];;
        }
        $delPermission = array_diff($newChildARR,$newMenuARR);
        $addPermssion = array_diff($newMenuARR,$newChildARR);



            foreach($delPermission as $k=>$v) {
                if(!AuthItemChild::findOne(['child'=>$v,'parent'=>$roleName])->delete()){
                    throw new Exception("删除失败");
                }
            }
            foreach($addPermssion as $k=>$v) {
                $newChildModel = new AuthItemChild();
                $newChildModel->child = $v;
                $newChildModel->parent = $roleName;
                if(!$newChildModel->save())
                {
                    throw new Exception(json_encode($newChildModel->errors));
                }
            }


    }

    /**
     * @var 权限菜单ID组
     */
    public $menuARR;
    public $checked;
    public $newChildARR;

    /**
     * 获取权限菜单
     * @param null $name
     * @return array|bool            $beginTransaction->commit();
     */
    public function getLeftMenu($name=null)
    {
        if($name==null) {
            $this->checked = false;
        } else{
            $childARR = AuthItemChild::find()->select(['child'])->where(['parent'=>$name])->asArray()->all();
            foreach($childARR as $k=>$v) {
                $this->newChildARR[] = str_replace("Menu@","",$v['child']);
            }
        }
        $newMenu = new Menu();
        $treeList = $newMenu->tree_list();

        $menuIdARR = static::find()->select(['menu_id'])->asArray()->all();
        foreach($menuIdARR as $k=>$v) {
            $this->menuARR[] = $v['menu_id'];
        }

        $leftMenu = $this->ViewCate($treeList);

        return $leftMenu;
    }


    public function ViewCate($menu)
    {
        foreach ($menu as $v => $k) {
            if(!in_array($k->id,$this->menuARR)){
                continue;
            }
            if($this->newChildARR&&in_array($k->id,$this->newChildARR)){
                $this->checked = true;
            }else{
                $this->checked = false;
            }
            if (isset($k->tree_children) ) {
                $arrRe[] = ['text' => $k->name, 'id' => $k->id,'children'=> $this->ViewCate($k['tree_children'])];
            }
            else {
                $arrRe[] = ['text' => $k->name, 'id' => $k->id,'checked' => $this->checked ];
            }
        }
        return $arrRe;
    }
}
